#include <func.h>
#include "ds.h"
#include "tcpClientInit.h"
#include "login_sign.h"
#include "epoll.h"
#include "puts_gets.h"

int main(int argc, char *argv[])
{
    ARGS_CHECK(argc, 3);
    char arg1[256] = {0};
    memcpy(arg1, argv[1], strlen(argv[1]));
    char arg2[256] = {0};
    memcpy(arg2, argv[2], strlen(argv[2]));

    int sockfd;

    bool loginFlag = false;
    bool signFlag = false;
    cmd_t cmd;
    int ret = login_sign(&sockfd, arg1, arg2 ,&cmd);
    ERROR_CHECK(ret, -1, "login_sign");

    int epfd = epoll_create(1);
    ret = epollAdd(epfd, sockfd);
    ERROR_CHECK(ret, -1, "epollAdd");
    ret = epollAdd(epfd, STDIN_FILENO);
    ERROR_CHECK(ret, -1, "epollAdd");

    train_t trainMsg;
    
    char buf[4096];
    bool connectFlag = true;
    
    while (1)
    {
        struct epoll_event readySet[2];
        int readyNum = epoll_wait(epfd, readySet, 2, -1);
        for (int i = 0; i < readyNum; ++i)
        {
            if (readySet[i].data.fd == STDIN_FILENO)
            {
                bzero(buf, sizeof(buf));
                ssize_t sret = read(STDIN_FILENO, buf, sizeof(buf));
                buf[sret - 1] = '\0';

                bzero(&cmd.parameter1, 256);
                bzero(&cmd.parameter2, 256);
                


                ret = commandAnalyze(buf, &cmd);
                if (ret == 1)
                {
                    continue;
                }

                transCommand(sockfd, &cmd);
                if (cmd.cmdType == CMD_PUTS)
                {
                    putsfiles(&cmd, sockfd);
                }
                if (cmd.cmdType == CMD_GETS)
                {
                    getsfiles(&cmd, sockfd);
                }
            }
            else
            {
                bzero(&trainMsg, sizeof(trainMsg));
                ssize_t sret = recv(sockfd, &trainMsg, sizeof(trainMsg), 0);
                if (sret == 0)
                {
                    connectFlag = false;
                    break;
                }
<<<<<<< HEAD
               // if (trainMsg.flag == TRAIN_FILE){
                 //   getsfiles(&cmd, sockfd);
                //}
=======
                // if (trainMsg.flag == TRAIN_FILE){
                //     getsfiles(&cmd, sockfd);
                // }
>>>>>>> 6baa695c1701cfddeb4b60674dba49ef257aa9b7
                if (trainMsg.flag == TRAIN_RESULT)
                {
                    printf("%s", trainMsg.data);
                }
            }
        }
        if (connectFlag == false)
        {
            break;
        }
    }
    return 0;
}
